jQuery(function () {
	// initialize widget elements
	d = document;
	var main = d.getElementById('main');
	var logDiv = d.createElement('div');
	logDiv.id = 'log';
	logDiv.style.left = (d.body.clientWidth - 300) + 'px';
	main.appendChild(logDiv);

	// include gg-ng-feeddy.css
	var cssLink = d.createElement('link');
	cssLink.setAttribute('rel', 'stylesheet');
	cssLink.setAttribute('type', 'text/css');
	cssLink.setAttribute('href', 'style.css?q=' + new Date().getTime());
	d.getElementsByTagName('head')[0].appendChild(cssLink);

	// TODO: get user preferences
	var feed = '../../tests/SampleFeed.xml';

	// load feed
	_IG_FetchXmlContent(feed, function (response, textStatus) {
		log('Content fetching status: ' + textStatus);
		if ('string' == typeof response) {
			response = getDomAdapter().parseXml(response);
		}
		var r = $(response);
		var elements = {'main' : d.getElementById('main'), 'toolbar' : {}};
		elements.main.appendChild(c('div', {'id' : 'channel'}, {}, [
			c('a', {'id' : 'channel-title', 'href' : r.find('channel>link').text()}, {}, r.find('channel>title').text())
		]));
		elements.main.appendChild(c('div', {'id' : 'toolbar'}, {}, [
			elements.toolbar.detailsOn = c('a', {'id' : 'toolbar-btn-details-on', 'href' : '#', 'className' : 'label-on'}, {}, ['details'], {'click' : function () {
				elements.toolbar.detailsOn.style.display = 'none';
				elements.toolbar.detailsOff.style.display = '';
			}}),
			elements.toolbar.detailsOff = c('a', {'id' : 'toolbar-btn-details-off', 'href' : '#', 'className' : 'label-off'}, {}, ['details'], {'click' : function () {
				elements.toolbar.detailsOn.style.display = '';
				elements.toolbar.detailsOff.style.display = 'none';
			}}),
			elements.toolbar.feeddy = c('a', {'id' : 'toolbar-btn-feeddy', 'href' : '#', 'className' : 'label'}, {}, ['feeddy'], {'click' : function () {
				window.open('http://fusion.google.com/add?moduleurl=http://hosting.gmodules.com/ig/gadgets/file/118415708682603388395/feeddy.xml');
			}}),
			elements.toolbar.help = c('a', {'id' : 'toolbar-btn-help', 'href' : '#', 'className' : 'label'}, {}, ['?'], {'click' : function () {
				window.open('Help!');
			}})
		]));
		elements.toolbar.detailsOn.style.display = 'none';
		elements.items = $(elements.main.appendChild(c('div', {'id' : 'items'})));
		r.find('item').each(function (index, item) {
			var i = $(item);
			elements.items.append('<div class="s' + ((index % 2) + 1)  + '"><a href="'
				+ i.find('link').text() + '">' + i.find('title').text() + '</a></div>');
		});
	});

});

function getDomAdapter()
{
	var adapter = '';
	if ('undefined' != typeof ActiveXObject) {
		adapter = 'MS';
	} else if ('undefined' != typeof document
		&& document.implementation
		&& document.implementation.createDocument
		&& 'undefined' != typeof DOMParser)
	{
		adapter = 'default';
	}
	switch (adapter) {
		case 'MS':
			return new (function () {
				this.createDocument = function () {
					var names = ["Msxml2.DOMDocument.6.0",
						"Msxml2.DOMDocument.3.0", "MSXML2.DOMDocument",
						"MSXML.DOMDocument", "Microsoft.XMLDOM"];
					for (var key in names) {
						try {
							return new ActiveXObject(names[key]);
						} catch (e) {}
					}
					throw new Error('Unable to create DOMDocument');
				};
				this.serialize = function (doc) {
					return doc.xml;
				};
				this.parseXml = function (xml) {
					var doc = this.createDocument();
					if (!doc.loadXML(xml)) {
						throw new Error('Parse error');
					}
					return doc;
				};
			})();
		case 'default':
			return new (function () {
				this.createDocument = function () {
					return document.implementation.createDocument("", "", null);
				};
				this.serialize = function (doc) {
					return new XMLSerializer().serializeToString(doc);
				};
				this.parseXml = function (xml) {
					var doc = new DOMParser().parseFromString(xml, "text/xml");
					if ("parsererror" == doc.documentElement.nodeName) {
						throw new Error('Parse error');
					}
					return doc;
				};
			})();
		default:
			throw new Error('Unable to select the DOM adapter');
	}
};

function log(msg) {
	var l = d.getElementById('log');
	if (l) l.insertBefore(d.createElement('pre'), null).appendChild(d.createTextNode(msg));
}

function c(name, attributes, css, content, handlers) {
	var e = d.createElement(name);
	var $e = $(e);
	if (attributes) for (var key in attributes) {
		e[key] = attributes[key];
	}
	if (css) $e.css(css);
	if (content) {
		if ('string' == typeof content) {
			$e.html(content);
		} else {
			for (var key in content) {
				if ('string' == typeof content[key]) {
					e.appendChild(d.createTextNode(content[key]));
				} else {
					e.appendChild(content[key]);
				}
			}
		}
	}
	if (handlers) for (var key in handlers) {
		$e[key](handlers[key]);
	}
	return e;
}
